<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/5 0005
 * Time: 上午 9:12
 * 企业付款工具类
 */
namespace app\common\controller;
class EnterpriseTools {
    /**
     * @param $wx_openid 某公众号下面某用户的唯一标识wx_openid
     * @param $amount 转账金额
     * @param $desc
     * @param string $order_number
     */
    public static  function  pay($wx_openid,$amount,$desc,$order_number=''){
        //读取配置文件
        //weixinConfig
        $weixinConfig=config("packet");
        //请求接口链接
        $pay_url="https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        $appid=$weixinConfig['appId'];//公众号appid
        $mch_id=$weixinConfig['mch_id'];//商户号
        $nonce_str=EnterpriseTools::createNonceStr(30);//随机字符串
        if(empty($order_number)){
             $order_number=EnterpriseTools::getOrderNo();//订单编号
        }
        $ip=get_ip();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $data['mch_appid']=$appid;
        $data['mchid']=$mch_id;
        $data['nonce_str']=$nonce_str;
        $data['partner_trade_no']=$order_number;
        $data['wx_openid']=$wx_openid;
        $data['check_name']="NO_CHECK";
        $data['amount']=$amount;
        $data['desc']=$desc;
        $data['spbill_create_ip']=$ip;
        $sign= EnterpriseTools::getSign($data);
        //组装请求参数
        $xml="<xml>";
        $xml=$xml."<mch_appid>".$appid."</mch_appid>";
        $xml=$xml."<mchid>".$mch_id."</mchid>";
        $xml=$xml."<nonce_str>".$nonce_str."</nonce_str>";
        $xml=$xml."<partner_trade_no>".$order_number."</partner_trade_no>";
        $xml=$xml."<wx_openid>".$wx_openid."</wx_openid>";
        $xml=$xml."<check_name>NO_CHECK</check_name>";
        /*    $xml=$xml."<re_user_name>张三</re_user_name>";*/
        $xml=$xml."<amount>".$amount."</amount>";
        $xml=$xml."<desc>".$desc."</desc>";
        $xml=$xml."<spbill_create_ip>".$ip."</spbill_create_ip>";
        $xml=$xml."<sign>".$sign."</sign>";
        $xml=$xml."</xml>";
       // return Enterprise::xmlToArray($xml);
        $res=EnterpriseTools::postXmlSSLCurl($pay_url,$xml);
        return $res;
        $result_=EnterpriseTools::xmlToArray($res);
       return $result_;
    }

    /**
     * 生成订单编号
     * @return string
     */
  public  static function getOrderNo() {
        $num1 = mt_rand(10000000, 99999999);
        $ordernumber = '21' . date('Ymd', time()) . $num1;
        return $ordernumber;
    }

    /**
     * 生成随机字符串
     * @param int $length
     * @return string
     */
    public static function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
     /**
      * 使用公众号证书，向微信提交post请求
      * 作用：使用证书，以post方式提交xml到对应的接口url
      * @param $url 请求的接口地址
      * @param $xml 请求的参数
      * @return  $rs 微信返回来的xml的参数
      */
    public static function postXmlSSLCurl($url,$xml,$second=30)
    {
        //weixinConfig
        $packet=config("packet");
        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,1);//证书检查
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
        curl_setopt($ch,CURLOPT_SSLCERT,$packet['CURLOPT_SSLCERT']);
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
        curl_setopt($ch,CURLOPT_SSLKEY,$packet['CURLOPT_SSLKEY']);
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
        curl_setopt($ch,CURLOPT_CAINFO,$packet['CURLOPT_CAINFO']);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
        $data=curl_exec($ch);
        if($data){ //返回来的是xml格式需要转换成数组再提取值，用来做更新
            curl_close($ch);
            return $data;
        }else{
            $error=curl_errno($ch);
            echo "curl出错，错误代码：$error"."<br/>";
            // echo "<a href='http://curl.haxx.se/libcurl/c/libcurs.html'>;错误原因查询</a><br/>";
            curl_close($ch);
            return false;
        }
    }

    /**
     * 获取签名
     * @param $arr 参与签名的参数
     * @return string 返回签名
     */
    public  static  function getSign($arr)
    {
        //读取配置文件，
        //weixinConfig
        $weixinConfig=config("packet");
        $api_key=$weixinConfig['api_key'];
        foreach ($arr as $k => $v)
        {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = EnterpriseTools::formatBizQueryParaMap($Parameters, false);//方法如下
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        $String = $String."&key=".$api_key;
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result;
    }
    /**
     * 作用：格式化参数，签名过程需要使用
     */
   public  static function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
                $v = urlencode($v);
            }

              $buff .= $k . "=" . $v . "&";
          }
        $reqPar=null;
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }
    //将XML转为array
    static function  xmlToArray($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }
}